<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>玉灵 QQ:7031633 Email:webrx@126.com</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/layer/3.1.1/layer.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/spark-md5/3.0.0/spark-md5.js"></script>
    <style>
        html, body {
            position: relative;
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
        }

        #drag-show {
            padding-top: 40px;
            line-height: 60px;
            text-align: center;
        }

        .show-area {
            display: inline-block;
            height: 60px;
            line-height: 60px;
            width: 180px;
            border: 1px dashed #c3c3c3;
            border-radius: 5px;
            vertical-align: middle;
        }

        .title {
            display: inline-block;
            line-height: 60px;
            color: #555;
            font-size: 20px;
            vertical-align: middle;
        }

        .img-box {
            position: relative;
            display: inline-block;
            width: 50px;
            height: 50px;
            line-height: 50px;
            margin-right: 8px;
            vertical-align: middle;
            cursor: pointer;
        }

        .img-span {
            display: inline-block;
            width: 100%;
            height: 100%;
            vertical-align: middle;
            overflow: hidden;
        }

        .img-item {
            display: inline-block;
            width: 100%;
            vertical-align: middle;
        }

        .del-icon {
            position: absolute;
            top: -7px;
            right: -7px;
            width: 14px;
            height: 14px;
            background-image: url('./del.png');
            background-size: 100% 100%;
            cursor: pointer;
        }

        #drag-area {
            position: relative;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            left: 50%;
            width: 300px;
            height: 200px;
            margin-left: -150px;
            margin-top: 20px;
            border-radius: 12px;
            border: 1px dashed #c3c3c3;
            outline: none;
            color: transparent;
            text-shadow: 0 0 0 #000;
        }

        .text {
            color: #555;
            font-size: 20px;
        }

        .upload-box {
            display: inline-block;
            width: auto;
            height: auto;
        }


        #upload {
            display: inline-block;
            width: 50px;
            height: 50px;
            padding: 8px;
            margin-top: 10px;
            box-sizing: border-box;
            border-radius: 5px;
            border: 1px dashed #c3c3c3;
            background-size: 100% 100%;
            background-image: url('./plus.png');
            cursor: pointer;
        }

        #upload:hover {
            background-color: #fafafa;
        }
    </style>
</head>

<body>

<div id="drag-show">
    <span class="title">图片展示区：</span>
    <span class="show-area"></span>
</div>
<!-- 图片拖拽区 -->
<div id="drag-area" contentEditable="true" ondragenter="drag(this, event);"
     ondragover="drag(this, event);"
     ondrop="dragUpload(this, event)"
     onpaste="pasteUpload(this, event);"
     onmouseenter="handleMouseEnter(this)"
     onmouseleave="handleMouseLeave(this)">
    <span class="text">将图片拖拽至此处上传</span>
    <div class="upload-box">
        <input type="file" name="file" multiple id="file" onchange="fileChange(this, event);"/>
        <span id="upload" onclick="uploadFile()"></span>
    </div>
</div>
<hr>
<button onclick="sh()">上传</button>
<hr>

<script>
    function sh(){
        let f = document.querySelector('input[name=file]')
        alert(f.files.length)
        for (const file of f.files) {
            console.log(file)
            console.log(file.name)
            console.log('aa')
        }
    }


    /** 图片存放数组 */
    const img_arr = [];
    /** 图片上传 */
    function upload(files) {
        const MAX_COUNT = 3;
        const IMG_COUNT = MAX_COUNT - img_arr.length;
        const additional_arr = [];
        const IMG_TYPES = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
        if (Array.prototype.some.call(files, function(file) {return !IMG_TYPES.includes(file.type)})) {
            layer.msg("图片格式不正确!!!")
            $("#file").val('');
            return;
        }

        if (files.length > IMG_COUNT) {
            layer.msg(`最多只能上传${MAX_COUNT}张图片!`)
            $("#file").val('');
            return;
        }

        Array.prototype.forEach.call(files, function(file, i, arr) {
            const fileReader = new FileReader();
            const sparkMD5 = new SparkMD5();
            fileReader.readAsDataURL(file);
            fileReader.onload = (event) => {
                const binary =  event.target.result; // 得到data url
                // 生成图片hash
                const hash = sparkMD5.appendBinary(binary).end();
                // 判断是否存在相同的图片
                if (!isExists(hash)) {
                    additional_arr.push({
                        hash,
                        src: binary,
                        file
                    });
                } else {
                    // 中断文件流
                    fileReader.abort();
                    layer.msg("请不要上传相同的图片!!!");
                }
            };
            fileReader.onloadend = (event) => {
                // 读取完成
                if (additional_arr.length === arr.length) {
                    img_arr.push(...additional_arr);
                    showImg(additional_arr); // 展示在展览区
                    $("#file").val('');
                }
            }
        })
    }

    // 判断是否有相同的图片
    function isExists(hash) {
        return img_arr.some(function(item) {
            return item.hash === hash;
        })
    }

    /** 控制删除icon */
    function imgMouseEnter(that) {
        $(that).find("span.del-icon").css('display', 'block');
    };

    function imgMouseLeave(that) {
        $(that).find("span.del-icon").css('display', 'none');
    }

    /** 展示图片 */
    function showImg(additional_arr) {
        if (!additional_arr.length) {
            return;
        }

        const img_html = additional_arr.reduce(function(init, item) {
            init += `<span class="img-box" onmouseenter="imgMouseEnter(this);" onmouseleave="imgMouseLeave(this);">
      <span class="img-span"><img src="${item.src}" mode="widthFix" class="img-item" ondrag="imgDragOver(this, event);" ondragend="imgDragEnd(this, event);"/></span>
      <span class="del-icon" hash="${item.hash}" onclick="deleteImg(this)" style="display: none;"></span>
    </span>`
            return init;
        }, '');

        $(".show-area").append(img_html);
    }

    // 删除
    function deleteImg(that) {
        const hash = $(that).attr("hash");
        const $imgBox = $(that).parents(".img-box");
        $imgBox.remove();
        img_arr.splice(img_arr.findIndex(function(item) {
            return item.hash === hash;
        }), 1);
    }

    // 获取元素位置
    function getElementLeft(element){
        var actualLeft = element.offsetLeft;
        var current = element.offsetParent;

        while (current !== null){
            actualLeft += current.offsetLeft;
            current = current.offsetParent;
        }
        return actualLeft;
    }

    function getElementTop(element){
        var actualTop = element.offsetTop;
        var current = element.offsetParent;

        while (current !== null){
            actualTop += current.offsetTop;
            current = current.offsetParent;
        }
        return actualTop;
    }


    // 拖拽删除
    function imgDragOver(that, event) {
        console.log('start', event)
        const $showArea = $(that).parents(".show-area");
        $showArea.css("border", "1px solid #0065ff")
    }

    function imgDragEnd(that, event) {
        const hash = $(that).attr("hash");
        const $showArea = $(".show-area");
        const $imgBox = $(that).parents(".img-box");
        const width = $showArea[0].clientWidth;
        const height = $showArea[0].clientHeight;
        const origin = {
            x: getElementLeft($showArea[0]),
            y: getElementTop($showArea[0])
        };

        const target = {
            x: event.clientX,
            y: event.clientY
        }

        if (target.x - origin.x > width || target.x < origin.x || target.y - origin.y > height || target.y < origin.y) {
            $imgBox.remove();
            img_arr.splice(img_arr.findIndex(function(item) {
                return item.hash === hash;
            }), 1);
        }
        $showArea.css("border", "1px dashed #c3c3c3")
        console.log(width, height, origin, target)
    }

    /** 手动上传 */
    function uploadFile() {
        $("#file").click();
    }

    function fileChange(that, event) {
        const files = event.target.files;
        upload(files);
    }

    /** 防止拖拽图片时打开图片 */
    function drag(that, event) {
        var e = event || window.event;
        e.preventDefault()
        e.stopPropagation()
    }

    /** 拖拽上传 */
    function dragUpload(that, event) {
        var e = event || window.event;
        e.preventDefault()
        e.stopPropagation()
        const files = e.dataTransfer.files;
        upload(files);
    }

    /** 赋值粘贴上传 */
    function handleMouseEnter(that) {
        $(that).focus();
    }

    function handleMouseLeave(that) {
        $(that).blur();
    }

    function pasteUpload(that, event) {
        var e = event || window.event;
        e.preventDefault()
        e.stopPropagation()
        var files = e.clipboardData.files;
        upload(files);
    }
</script>
</body>
</html>
